import { usePermissionStoreHook } from "@/store/modules/permission";
import { useUserStoreHook } from "@/store/modules/user";
import router from "@/router";

const userStore = useUserStoreHook();

const permissionStore = usePermissionStoreHook();
// 白名单
const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
  // 是否登录
  const hasToken = userStore.accessToken;
  console.log("hasToken", hasToken);
  if (hasToken) {
    // 已登录
    if (to.path === "/login") {
      // 如果去登录页，跳转首页
      next({ path: "/" });
    } else {
      // 是否有权限
      if (permissionStore.asyncRoutes.length > 0) {
        next();
      } else {
        // 重新获取路由菜单
        // let accessRoutes = await permissionStore.generateRoutes();
        // accessRoutes.forEach((route) => {
        //   router.addRoute(route);
        // });
        next({ ...to, replace: true });
      }
    }
  } else {
    // 未登录
    if (whiteList.indexOf(to.path) !== -1) {
      // 白名单页面跳转
      next();
    } else {
      // 跳转到登录页
      next(`/login?redirect=${to.path}`);
    }
  }
});
